package com.huawei.crm.sample.infrastructure.outbound.persistence.order.repository.impl;

import com.huawei.crm.sample.domain.order.model.aggragate.Order;
import com.huawei.crm.sample.domain.order.repository.OrderRepository;
import com.huawei.crm.sample.infrastructure.outbound.persistence.order.converter.OrderPOConverter;
import com.huawei.crm.sample.infrastructure.outbound.persistence.order.dao.OrderDAO;
import com.huawei.crm.sample.infrastructure.outbound.persistence.order.dao.OrderItemDAO;
import com.huawei.crm.sample.infrastructure.outbound.persistence.order.po.OrderPO;
import com.huawei.crm.sample.infrastructure.outbound.persistence.order.po.OrderItemPO;
import com.huawei.crm.sample.domain.order.model.entity.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class OrderRepositoryImpl implements OrderRepository {
    @Autowired
    private OrderDAO orderDAO;
    @Autowired
    private OrderItemDAO orderItemDAO;
    @Autowired
    private OrderPOConverter orderPOConverter;

    @Override
    public void save(Order order) {
        OrderPO po = orderPOConverter.toPO(order);
        orderDAO.save(po);
        // 回填主键id
        order.setOrderId(po.getOrderId());
        List<OrderItemPO> itemPOs = orderPOConverter.toItemPOList(order.getItems());
        for (OrderItemPO itemPO : itemPOs) {
            itemPO.setOrderId(po.getOrderId());
            orderItemDAO.save(itemPO);
        }
    }

    @Override
    public Order findById(String orderId) {
        OrderPO po = orderDAO.getById(orderId);
        if (po == null) return null;
        List<OrderItemPO> itemPOs = orderItemDAO.list(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<OrderItemPO>().eq("order_id", orderId));
        List<OrderItem> items = orderPOConverter.toItemList(itemPOs);
        Order order = new Order();
        order.setOrderId(po.getOrderId());
        order.setCustomerId(po.getCustomerId());
        order.setItems(items);
        order.setCreatedAt(po.getCreatedAt());
        order.setStatus(po.getStatus());
        return order;
    }
} 